package com.compass.doctor.ui.prescription.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.asLiveData
import com.compass.framework.ext.stringListToJson
import com.compass.framework.model.Diagnosis
import com.compass.framework.model.PatientInfo
import com.compass.framework.model.PrescriptionInformation
import com.compass.framework.model.TemplateDetails
import com.compass.framework.toast.TipsToast
import com.compass.network.callback.IApiErrorCallback
import com.compass.network.manager.ApiManager
import com.compass.network.response.BaseResponse
import com.compass.network.viewmodel.BaseViewModel
import com.google.gson.Gson
import com.google.gson.JsonObject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
import org.json.JSONArray

/**
 * Description： 处方viewModel
 * Date:2023/12/15 14:34
 */
class PrescribeViewModel : BaseViewModel() {

    val historyPrescriptionTotalLiveData: MutableLiveData<Long?> = MutableLiveData()
    val diagnosisLiveData = MutableLiveData<MutableList<Diagnosis>?>()//诊断数据
    val createDiagnosisLiveData = MutableLiveData<Diagnosis?>()//创建诊断
    val templateLiveData = MutableLiveData<MutableList<TemplateDetails>?>()//历史模板
    val templateNumberLiveData = MutableLiveData<String?>()//历史模板数量
    val prescriptionRecordLiveData =
        MutableLiveData<MutableList<TemplateDetails>?>()//处方记录-个人中心/处方审核
    val historyPrescriptionLiveData = MutableLiveData<MutableList<TemplateDetails>?>()//历史处方-处方模板
    val historyPrescriptionNumberLiveData = MutableLiveData<String?>()//历史处方-处方模板数量

    val templateDetailsLiveData = MutableLiveData<TemplateDetails?>()
    val createLiveData = MutableLiveData<String?>()//创建处方
    val updateLiveData = MutableLiveData<Boolean>()
    val cancelLiveData = MutableLiveData<Boolean>()
    val examineLiveData = MutableLiveData<Boolean>()
    val deleteLiveData = MutableLiveData<Boolean>()
    val refuseLiveData = MutableLiveData<Boolean>()//续方拒绝


    /**
     * 历史处方-处方模板
     */
    fun getHisPrescription(
        pageNo: Int = 1,
        patientId: String?,
        status: ArrayList<String>?,
        startDate: Long?,
        endDate: Long?,
        ifTransfer: Int?,
        type: Int?,

    ) {

        val params = JsonObject().apply {
            addProperty("pageNo", pageNo)
            addProperty("pageSize", 10)
            add("status", stringListToJson(status))
            addProperty("timeType", 4)
            addProperty("startDate", startDate)
            addProperty("endDate", endDate)
            addProperty("patientId", patientId)
            addProperty("ifTransfer", ifTransfer)
            addProperty("type", type)
        }

        launchUIWithResult(responseBlock = {
            ApiManager.api.getHisPrescription(params)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTips(error)
                historyPrescriptionLiveData.value = null
            }
        }) {
            if (it == null || it.list.isNullOrEmpty()) {
                historyPrescriptionLiveData.value = null
            } else {
                historyPrescriptionNumberLiveData.value = it.total.toString()
                historyPrescriptionLiveData.value = it.list
            }
        }
    }


    /**
     * 处方审核 列表
     */
    fun getRxExamine(pageNo: Int = 1, status: String?) {
        val params = JsonObject().apply {
            addProperty("pageNo", pageNo)
            addProperty("pageSize", 10)
            addProperty("type", status)
        }

        launchUIWithResult(responseBlock = {
            ApiManager.api.getRxExamine(params)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTips(error)
                prescriptionRecordLiveData.value = null
            }
        }) {
            if (it == null || it.list.isNullOrEmpty()) {
                prescriptionRecordLiveData.value = null
            } else {
                prescriptionRecordLiveData.value = it.list
            }
        }
    }



    /**
     * 处方审核 列表
     */
    fun createDiagnosis( name: String?) {
        val params = JsonObject().apply {
            addProperty("name", name)
        }

        launchUIWithResult(responseBlock = {
            ApiManager.api.createDiagnosis(params)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTips(error)
                createDiagnosisLiveData.value=null
            }
        }) {
            createDiagnosisLiveData.value=it
        }
    }


    /**
     * 获取处方记录总金额
     *  @param status 这里的参数暂时不传
     */
    fun getHisPrescriptionTotal(status: ArrayList<String>?, startDate: Long?, endDate: Long?) {
        val params = JsonObject().apply {
//            add("status", stringListToJson(status))
//            addProperty("timeType", 4)
//            addProperty("startDate", startDate)
//            addProperty("endDate", endDate)

        }
        launchUIWithResult(responseBlock = {
            ApiManager.api.getHisPrescriptionTotal(params)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTips(error)
                historyPrescriptionTotalLiveData.value = null
            }
        }) {
            historyPrescriptionTotalLiveData.value = it
        }
    }


    /**
     * 处方记录-个人中心
     */
    fun getPrescriptionRecord(pageNo: Int = 1, status: String?) {
        val params = JsonObject().apply {
            addProperty("pageNo", pageNo)
            addProperty("pageSize", 10)
            addProperty("status", status)
        }

        launchUIWithResult(responseBlock = {
            ApiManager.api.getPrescriptionRecord(params)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTips(error)
                prescriptionRecordLiveData.value = null
            }
        }) {
            if (it == null || it.list.isNullOrEmpty()) {
                prescriptionRecordLiveData.value = null
            } else {
                prescriptionRecordLiveData.value = it.list
            }
        }
    }


    /**
     * 作废处方-医生
     */
    fun prescriptionCancel(id: String, cancelDescription: String? = "") {
        launchUIWithResult(responseBlock = {
            ApiManager.api.prescriptionCancel(id, cancelDescription)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTips(error)
                cancelLiveData.value = false
            }
        }) {
            it?.let {
                cancelLiveData.value = true
            }

        }
    }


    /**
     * 处方审核-药师
     */
    fun prescriptionExamine(id: String, status: String, cancelDescription: String? = "") {
        launchUIWithResult(responseBlock = {
            ApiManager.api.prescriptionExamine(id, status, cancelDescription)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTips(error)
                examineLiveData.value = false
            }
        }) {
            it?.let {
                examineLiveData.value = true
            }

        }
    }

    /**
     * 续方审核-医生
     */
    fun prescriptionRenewal(id: String, status: String) {
        launchUIWithResult(responseBlock = {
            ApiManager.api.prescriptionRenewal(id, status)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTips(error)
                refuseLiveData.value = false
            }
        }) {
            refuseLiveData.value = true
        }
    }

    /**
     * 获取诊断
     */
    fun getDiagnosisInfo(keyword: String = "", type: String?) {
        launchUIWithResult(responseBlock = {
            ApiManager.api.getDiagnosisInfo(keyword, type)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTips(error)
                diagnosisLiveData.value = null
            }
        }) {
            diagnosisLiveData.value = it
        }
    }

    /**
     * 模板详情
     * 模板是2
     */
    fun getTemplateDetails(id: String?, type: String?) {
        launchUIWithResult(responseBlock = {
            ApiManager.api.getTemplateDetails(id, type)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTips(error)
            }
        }) {
            templateDetailsLiveData.value = it
        }
    }

    /**
     * 获取处方详情
     * 处方是1
     */
    fun getPrescriptionDetails(id: String?, type: String?) {
        launchUIWithResult(responseBlock = {
            ApiManager.api.getPrescriptionDetails(id, type)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTips(error)
            }
        }) {
            templateDetailsLiveData.value = it
        }
    }

    /**
     * 删除模板
     */
    fun deleteTemplate(id: String?) {
        launchUIWithResult(responseBlock = {
            ApiManager.api.deleteTemplate(id)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTips(error)
                deleteLiveData.value = false
            }
        }) {
            it?.let {
                deleteLiveData.value = true
            }


        }
    }

    /**
     * 获取模板列表
     */
    fun getTemplateList(page: Int) {
        launchUIWithResult(responseBlock = {
            ApiManager.api.getTemplate(page = page, pageSize = 10)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTips(error)
                templateLiveData.value = null
            }
        }) {
            if (it == null || it.list.isNullOrEmpty()) {
                templateLiveData.value = null
            } else {
                templateNumberLiveData.value = it.total.toString()
                templateLiveData.value = it.list
            }
        }
    }


    /**
     * 创建处方
     */
    fun prescriptionCreate(rxInformation: PrescriptionInformation) {
        launchUIWithResult(responseBlock = {
            ApiManager.api.prescriptionCreate(rxInformation)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTipsLong(error)
                createLiveData.value = null
            }
        }) {
            createLiveData.value = it
        }
    }

    /**
     * 创建模板
     */
    fun templateCreate(rxInformation: PrescriptionInformation) {
        launchUIWithResult(responseBlock = {
            ApiManager.api.templateCreate(rxInformation)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                createLiveData.value = null
            }
        }) {
            createLiveData.value = it
        }
    }


    /**
     * 更新模板
     */
    fun templateUpdate(rxInformation: PrescriptionInformation) {

        launchUIWithResult(responseBlock = {
            ApiManager.api.templateUpdate(rxInformation)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                super.onError(code, error)
                updateLiveData.value = false
            }
        }, successBlock = {
            it?.let {
                updateLiveData.value = true
            }
        })
    }


    //模拟自动搜索业务
    private val _searchStateFlow = MutableStateFlow("")

    //根据关键词搜索
    fun queryDiagnosis(parameter: String) {
        _searchStateFlow.value = parameter
    }

    val searchResult =
        // 避免在单位时间内，快输入造成大量的请求
        _searchStateFlow.debounce(500)
            //避免重复的搜索请求。假设正在搜索 dhl，用户删除了 l  然后输入 l。最后的结果还是 dhl。它就不会再执行搜索查询 dhl
            .distinctUntilChanged()
            .filter { result ->
                return@filter result.isNotEmpty()
            }.flatMapLatest {// 只显示最后一次搜索的结果，忽略之前的请求
                    parameter ->
                //网络请求，这里替换自己的实现即可(或者本地请求)
                searchDiagnose(parameter)
            }.asLiveData()

    //诊断搜索 将一个普通的api接口包装成Flow返回值
    private fun searchDiagnose(parameter: String): Flow<BaseResponse<MutableList<PatientInfo>>?> {
        return flow {
//            ApiManager.api.getPatientInfo().let {
//                emit(it)
//            }
        }

    }

}